package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.bean.GroupInfo;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.system.domain.AppGroupUser;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.service.IAppGroupUserService;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.web.controller.common.GroupInfoDTO;
import io.swagger.models.auth.In;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.AppGroupInfo;
import com.ruoyi.system.service.IAppGroupInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 群组信息Controller
 *
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/system/info")
public class AppGroupInfoController extends BaseController {
    @Autowired
    private IAppGroupInfoService appGroupInfoService;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppGroupUserService iAppGroupUserService;

    /**
     * 查询群组信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppGroupInfo appGroupInfo) {
        startPage();
        List<AppGroupInfo> list = appGroupInfoService.selectAppGroupInfoList(appGroupInfo);
        for (AppGroupInfo groupInfo : list) {
            if (groupInfo.getIsExit() != null) {
                if (groupInfo.getIsExit() == 0) {
                    groupInfo.setExitEnable(true);
                }
                if (groupInfo.getIsExit() == 1) {
                    groupInfo.setExitEnable(false);
                }
            }
            if (groupInfo.getIsDefault() != null) {
                if (groupInfo.getIsDefault() == 0) {
                    groupInfo.setDefaultEnable(true);
                }
                if (groupInfo.getIsDefault() == 1) {
                    groupInfo.setDefaultEnable(false);
                }
            }

            if (groupInfo.getFreezeState() != null) {
                if (groupInfo.getFreezeState() == 1) {
                    groupInfo.setFreezeStateEnable(true);
                }
                if (groupInfo.getFreezeState() == 0) {
                    groupInfo.setFreezeStateEnable(false);
                }
            }

            QueryWrapper<AppGroupUser> ew = new QueryWrapper<>();

            List<String> greupUserIds = Lists.newArrayList();
            greupUserIds.add(groupInfo.getGroupId());
            List<GroupInfo> groupInfos = tencentCloudImUtil.getGroupInfo(greupUserIds);
            if (groupInfos.size() > 0) {
                groupInfo.setGroupName(groupInfos.get(0).getName());
                groupInfo.setGroupNum(groupInfos.get(0).getMemberNum());
            } else {
                groupInfo.setGroupNum(0);
            }
            // 关联群主名称
            AppUser appUser = iAppUserService.getById(groupInfo.getUserId());
            if (appUser != null) {
                groupInfo.setUserName(appUser.getUsername());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出群组信息列表
     */
    @Log(title = "群组信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppGroupInfo appGroupInfo) {
        List<AppGroupInfo> list = appGroupInfoService.selectAppGroupInfoList(appGroupInfo);
        ExcelUtil<AppGroupInfo> util = new ExcelUtil<AppGroupInfo>(AppGroupInfo.class);
        util.exportExcel(response, list, "群组信息数据");
    }

    /**
     * 获取群组信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appGroupInfoService.selectAppGroupInfoById(id));
    }

    /**
     * 新增群组信息
     */
    @Log(title = "群组信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppGroupInfo appGroupInfo) {
        return toAjax(appGroupInfoService.insertAppGroupInfo(appGroupInfo));
    }

    /**
     * 修改群组信息
     */
    @Log(title = "群组信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppGroupInfo appGroupInfo) {
        return toAjax(appGroupInfoService.updateAppGroupInfo(appGroupInfo));
    }

    /**
     * 删除群组信息
     */
    @Log(title = "群组信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(appGroupInfoService.deleteAppGroupInfoByIds(ids));
    }

    @Log(title = "解散群", businessType = BusinessType.DELETE)
    @DeleteMapping("/destroyGroup/{ids}")
    public AjaxResult destroyGroup(@PathVariable Long[] ids) {
        appGroupInfoService.destroyGroup(ids);
        return success();
    }

    @Log(title = "清空聊天记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/clearGroupAttr/{ids}")
    public AjaxResult clearGroupAttr(@PathVariable Long[] ids) {
        appGroupInfoService.clearGroupAttr(ids);
        return success();
    }

    /**
     * 获取历史消息
     *
     * @param groupInfoDTO
     * @return
     */
    @GetMapping("/getMsgPage")
    public AjaxResult getMsgPage(GroupInfoDTO groupInfoDTO) {
        String result = tencentCloudImUtil.getGroupMsgPage(groupInfoDTO.getGroupId(), groupInfoDTO.getReqMsgSeq(), groupInfoDTO.getReqMsgNumber());
        JSONObject res = JSONObject.parseObject(result);
        if (res.getIntValue("ErrorCode") == 0) {
            return AjaxResult.success(res);
        } else {
            return AjaxResult.error(res.getString("ErrorInfo"));
        }

    }

    /**
     * 合并群
     *
     * @param groupInfoDTO
     * @return
     */
    @PostMapping("/changeGroup")
    public AjaxResult changeGroup(@RequestBody GroupInfoDTO groupInfoDTO) {

        QueryWrapper<AppGroupUser> qw = new QueryWrapper<>();
        qw.eq("group_id", groupInfoDTO.getBeGroupId());
        List<Object> userIds = iAppGroupUserService.listObjs(qw.select("user_id"));
        // 删除 群和用户绑定表信息
        iAppGroupUserService.remove(qw);

        if (userIds.size() > 0) {
            List<AppUser> users = iAppUserService.getListByUserIds(userIds);
            List<Map<String, Object>> MemberLists = Lists.newArrayList();
            for (AppUser appUser : users) {
                Map<String, Object> map = new HashMap<>();
                map.put("Member_Account", appUser.getAccount());
                MemberLists.add(map);
            }
            // 转移用户至 指定群中
            String result = tencentCloudImUtil.groupsAddUsers(MemberLists, groupInfoDTO.getGroupId(), null);
            JSONObject res = JSONObject.parseObject(result);
            if (res.getIntValue("ErrorCode") == 0) {
                appGroupInfoService.destroyGroupId(groupInfoDTO.getBeGroupId());
                return AjaxResult.success();
            } else {
                return AjaxResult.error("合并失败");
            }
        } else {
            appGroupInfoService.destroyGroupId(groupInfoDTO.getBeGroupId());
            // 解散被合并的群
            return AjaxResult.success();
        }
    }

}
